/* eslint-disable no-nested-ternary */
/* eslint-disable react/jsx-key */
import React from 'react';
import PropTypes from 'prop-types';
import {columns} from './constants';
import DataSet from '@antv/data-set';
import {partOrderList} from '../Enum';
import {Table, Form, Card, Row, Col} from 'antd';
import {injectIntl, formatMessage} from './intl';
import TagSelect from 'Shared/components/TagSelect';
import {FORM_ROW_OPTIONS, TABLE} from '../constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {Chart, Geom, Axis, Tooltip, Label, View} from 'bizcharts';
export class TablePanelCountry extends React.PureComponent {
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearchCountry(value);
    }
    render() {
        const {conditions, dataCountry, initEnum, loading} = this.props;
        const countryCrop = [];
        dataCountry.forEach(item => {
            const arr = conditions.type === partOrderList.品种满足率 ? item.details.map(v => ({
                month: v.month,
                PI项数: v.piVarietyQty,
                备货项数: v.deliveryVarietyQty,
                品种满足率: v.varietyMeetRate
            })) : conditions.type === partOrderList.金额满足率 ? item.details.map(v => ({
                month: v.month,
                PI金额: v.piAmount,
                备货金额: v.deliveryAmount,
                金额满足率: v.amountMeetRate
            })) : item.details.map(v => ({
                month: v.month,
                PI数量: v.piQuantity,
                备货数量: v.deliveryQuantity,
                数量满足率: v.quantityMeetRate
            }));
            //柱状图与折线图
            const dsRate = new DataSet();
            dsRate.setState('type', '');
            arr.pop();
            const dvRate = dsRate.createView().source(arr);
            const pval = conditions.type === partOrderList.品种满足率
                ? 'PI项数'
                : conditions.type === partOrderList.金额满足率
                    ? 'PI金额'
                    : 'PI数量';
            const pname = conditions.type === partOrderList.品种满足率
                ? '备货项数'
                : conditions.type === partOrderList.金额满足率
                    ? '备货金额'
                    : '备货数量';
            const ptype = conditions.type === partOrderList.品种满足率
                ? '品种满足率'
                : conditions.type === partOrderList.金额满足率
                    ? '金额满足率'
                    : '数量满足率';
            dvRate.transform({
                type: 'fold',
                fields: conditions.type === partOrderList.品种满足率
                    ? ['PI项数', '备货项数']
                    : conditions.type === partOrderList.金额满足率
                        ? ['PI金额', '备货金额']
                        : ['PI数量', '备货数量'],
                key: 'type', // key字段
                value: 'value', // value字段
            })
                .transform({
                    type: 'filter',
                    callback: d => d.type !== dsRate.state.type
                });
            const val = {
                type: 'linear',
                formatter: val => `${val.toFixed(2)}%`,
                tickCount: 10
            };
            const scale = conditions.type === partOrderList.品种满足率
                ? {
                    品种满足率: val,
                    value: {
                        alias: '品种\n满\n足\n率'
                    }
                } : conditions.type === partOrderList.金额满足率
                    ? {
                        金额满足率: val,
                        value: {
                            alias: '金额\n满\n足\n率'
                        }
                    } : {
                        数量满足率: val,
                        value: {
                            alias: '数量\n满\n足\n率'
                        }
                    };
            const chart = (
                <Chart forceFit data={dvRate} scale={scale}
                    style={{fontSize: '12'}}
                    height={400}
                    padding={['7%', '8%', '15%']}
                    onGetG2Instance={c => {
                        this.chart = c;
                    }}>
                    <Axis name="month" />
                    <Axis name="value" position={'left'} />
                    <Tooltip />
                    <Geom
                        type="interval"
                        position="month*value"
                        color={['type', value => {
                            if(value === pval)
                                return '#4F81BD';
                            if(value === pname)
                                return '#C0504D';
                        }]}
                        adjust={[{
                            type: 'dodge',
                            marginRatio: 1 / 1.5,
                        }]} >
                        <Label
                            content="value"
                            textStyle={{
                                textAlign: 'center', // 文本对齐方向，可取值为： start middle end
                                fill: '#404040', // 文本的颜色
                                fontSize: '12', // 文本大小
                            }}/>
                    </Geom>
                    <View data={arr} >
                        <Axis name={ptype} position="right" />
                        <Geom type="line" position={`month*${ptype}`} color="#98B954" size={3} >
                            <Label
                                content={ptype}
                                textStyle={{
                                    textAlign: 'center', // 文本对齐方向，可取值为： start middle end
                                    fill: '#404040', // 文本的颜色
                                    fontSize: '12', // 文本大小
                                }}/>
                        </Geom>
                    </View>
                </Chart>
            );
            countryCrop.push(
                <Card.Grid
                    style={{
                        width: '48%',
                        marginBottom: 15,
                        marginLeft: 15}}
                    key={item.id}>
                    <Card
                        bodyStyle={{padding: 0}}
                        bordered={false}
                        loading={loading}>
                        <Card.Meta
                            title={item.country}
                            description={<div>{chart}
                                <Table
                                    className="white-space-nowrap"
                                    rowKey="id"
                                    dataSource={item.details}
                                    columns={columns(conditions, item.details)}
                                    loading={loading}
                                    pagination={false}
                                    {...TABLE} />
                            </div>}/>
                    </Card>
                </Card.Grid>
            );
        });
        return (
            <Card>
                <Form className="form-standard">
                    <DescriptionList size="large" title={<Row><Col span={12}>
                        {formatMessage({
                            id: 'queryPanel.form.dealerquery',
                            defaultMessage: '总代汇总查询'
                        })}</Col></Row>}>
                        <Form.Item label={formatMessage({
                            id: 'queryPanel.form.dealerId',
                            defaultMessage: '总代'
                        })} {...FORM_ROW_OPTIONS.item}>
                            <TagSelect
                                name="dealerId"
                                value={conditions.dealerId}
                                options={initEnum.dealers}
                                onChange={this.handleFilterChange} />
                        </Form.Item>
                        <div style={{height: 30}} />
                        {conditions.dealerId.length > 0 && countryCrop}
                    </DescriptionList>
                </Form>
            </Card>
        );
    }
}

TablePanelCountry.propTypes = {
    conditions: PropTypes.object.isRequired,
    dataCountry: PropTypes.array.isRequired,
    querySearchCountry: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    loading: PropTypes.bool,
};

import {connect} from 'react-redux';
import * as actions from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'data']),
    init => {
        const initData = init.toJS();
        const dealers = initData ? initData.map(item => ({
            text: `${'('}${item.code}${')'}${item.country}`,
            value: item.id
        })) : [];
        return {
            dealers
        };
    }
);

const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getDataCountry = selectorFactory(['page', 'domainData', 'listCountry', 'data']);
const mapStateToProps = state => ({
    initEnum: getInitData(state),
    conditions: getConditions(state),
    dataCountry: getDataCountry(state),
    loading: state.getIn(['page', 'domainData', 'listCountry', 'isFetching']),
});
const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(actions.saveQueryCondition(name, value)),
    querySearchCountry: value => dispatch(actions.querySearchCountry(value))
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanelCountry));
